import { Component } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { DialogService, DValidateRules, FormLayout, TableWidthConfig } from 'ng-devui';
import { PurchaseReturnedOrder } from 'src/app/@core/data/purchase';
import { CustomerService } from 'src/app/@core/services/customer/customer.service';
import { DataSharingService } from 'src/app/@core/services/dataSharing/data-sharing.service';
import { PurchaseService } from 'src/app/@core/services/purchase/purchase.service';
import { UserService } from 'src/app/@core/services/user/user.service';
import { AttachmentComponent } from 'src/app/@shared/components/attachment/attachment.component';
import { SelectInventoryComponent } from 'src/app/@shared/components/select-inventory/select-inventory.component';
import { SelectSupplierComponent } from 'src/app/@shared/components/select-supplier/select-supplier.component';
import { SelectUserComponent } from 'src/app/@shared/components/select-user/select-user.component';
import { environment } from 'src/environments/environment';
import { SelectArrivalComponent } from '../select-arrival/select-arrival.component';
import { ReviewRolesService } from 'src/app/@core/services/ReviewRoles/review-roles.service';

@Component({
  selector: 'app-purchase-return-edit',
  templateUrl: './purchase-return-edit.component.html',
  styleUrls: ['./purchase-return-edit.component.scss']
})
export class PurchaseReturnEditComponent {
  Math = Math;
  msgs: Array<Object> = [];
  UrlHead: any = environment.modifiedApiUrl
  layoutDirection: FormLayout = FormLayout.Horizontal;
  tableWidthConfig: TableWidthConfig[] = [
    {
      field: '操作',
      width: '150px'
    },
    {
      field: '物料编码',
      width: '150px'
    },
    {
      field: '图片',
      width: '150px'
    },
    {
      field: '物料名称',
      width: '150px'
    },
    {
      field: '物料规格',
      width: '150px'
    },
    {
      field: '物料描述',
      width: '150px'
    },
    {
      field: '物料单位',
      width: '150px'
    },
    {
      field: '未到货数',
      width: '200px'
    },
    {
      field: '到货日期',
      width: '200px'
    },
    {
      field: '仓库',
      width: '200px'
    },
    {
      field: '库位',
      width: '200px'
    },
    {
      field: '到货数量',
      width: '200px'
    },
    {
      field: '单价(含税)',
      width: '200px'
    },
    {
      field: '税率',
      width: '200px'
    },
    {
      field: '不含税单价',
      width: '150px'
    },
    {
      field: '含税金额',
      width: '150px'
    },
    {
      field: '不含税金额',
      width: '150px'
    },
    {
      field: '税额',
      width: '150px'
    },
    {
      field: '来源单号',
      width: '150px'
    },
    {
      field: '备注',
      width: '150px'
    }
  ];//表格宽度配置
  taxRate: number = 13
  customerContact: any
  loadData: boolean

  purchaseReturnOrder: PurchaseReturnedOrder = {
    purchaseReturnedOrderId: 0, // 采购退货订单ID，初始化为0
    purchaseReturnedOrderNum: '', // 采购退货订单编号，初始化为空字符串
    orderDate: null, // 订单日期，初始化为null
    proSupplyId: 0, // 供应商ID，初始化为0
    supplyShortName: '', // 供应商简称，初始化为空字符串
    supplyChineseName: '', // 供应商中文名，初始化为空字符串
    supplyEnglishName: '', // 供应商英文名，初始化为空字符串
    supplyNum: '', // 供应商编号，初始化为空字符串
    supplyContactName: '', // 供应商联系人姓名，初始化为空字符串
    supplyContactId: 0, // 供应商联系人ID，初始化为0
    address: '', // 地址，初始化为空字符串
    purchaseManName: '', // 采购员姓名，初始化为空字符串
    purchaseManId: 0, // 采购员ID，初始化为0
    departmentName: '', // 部门名称，初始化为空字符串
    departmentId: 0, // 部门ID，初始化为0
    proSettlementMethodId: 0, // 结算方式ID，初始化为0
    settlementMethodName: '', // 结算方式名称，初始化为空字符串
    proCurrencyId: 0, // 货币ID，初始化为0
    currencyName: '', // 货币名称，初始化为空字符串
    proCollectionPeriodId: 0, // 收款期限ID，初始化为0
    collectionPeriodName: '', // 收款期限名称，初始化为空字符串
    remark: '', // 备注，初始化为空字符串
    status: '未开始审核', // 状态，初始化为空字符串
    isClosed: false, // 是否关闭，初始化为false
    isReturned: false, // 是否退货，初始化为false
    returnedQuantity: 0, // 退货数量，初始化为0
    totalAmountWithTax: 0, // 含税总金额，初始化为0
    totalTaxAmount: 0, // 税额总计，初始化为0
    totalAmountWithoutTax: 0, // 不含税总金额，初始化为0
    createDate: null, // 创建日期，初始化为null
    creator: '', // 创建者，初始化为空字符串
    files: [], // 文件列表，初始化为空数组
    fileRemarks: [], // 文件备注列表，初始化为空数组
    purchaseReturnedOrderParts: [
      {
        purchaseReturnedOrderPartId: 0, // 采购退货订单物料行ID，初始化为0
        partNum: '', // 物料编号，初始化为空字符串
        partUOM: '', // 物料单位，初始化为空字符串
        partName: '', // 物料名称，初始化为空字符串
        description: '', // 物料描述，初始化为空字符串
        partType: '', // 规格型号，初始化为空字符串
        image: '', // 图片，初始化为空字符串
        returnedQuantity: 0, // 退货数量，初始化为0
        returnedDate: null, // 退货日期，初始化为undefined
        warehouseId: 0, // 仓库ID，初始化为0
        warehouseName: '', // 仓库名称，初始化为空字符串
        warehouseNum: '', // 仓库编号，初始化为空字符串
        positionId: 0, // 位置ID，初始化为0
        positionName: '', // 位置名称，初始化为空字符串
        positionNum: '', // 位置编号，初始化为空字符串
        priceWithTax: 0, // 含税价格，初始化为0
        priceWithoutTax: 0, // 不含税价格，初始化为0
        taxRate: 0, // 税率，初始化为0
        amountWithTax: 0, // 含税金额，初始化为0
        amountWithoutTax: 0, // 不含税金额，初始化为0
        taxAmount: 0, // 税额，初始化为0
        propPartId: 0, // 部件ID，初始化为0
        alreadyReturnedQuantity: 0, // 已退货数量，初始化为0
        note: '', // 备注，初始化为空字符串
        purchaseArrivalOrderNum: '', // 采购到货订单编号，初始化为空字符串
        purchaseArrivalOrderPartId: 0, // 采购到货订单物料行ID，初始化为0
        propPurchaseReturnedId: 0, // 采购退货订单ID，初始化为0
        purchaseReturnedOrderNum: '' // 采购退货订单编号，初始化为空字符串
      }
    ]
  }
  purchaseReturnOrderRules: { [key: string]: DValidateRules } = {
    purchaseArrivalNum: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*采购需求单单号不能为空' },
        { minlength: 2, message: '*采购需求单单号长度至少为2' },
        { maxlength: 40, message: '*采购需求单单号长度至多为40' },
        { pattern: /^[^\s]*$/, message: '*采购需求单单号不能包含空格' }
      ]
    },
    purchaseManName: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*业务员不能为空' },
      ]
    },
    advicePurchaseDate: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*建议申请时间不能为空' },
      ]
    },
    partNum: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*物料不能为空' },
      ]
    },
    purchaseDate: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*建议采购时间不能为空' },
      ]
    },
    purchaseQuantity: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*建议采购数量不能为空' },
      ]
    }
  }
  supplyContactOption = [] // 供应商联系人
  supplyContact = {}//供应商联系人
  settlementMethodOption = [] // 结算方式
  settlementMethod = {}//结算方式
  currencyOption = [] // 交易币种
  currency = {}//交易币种
  collectionPeriodOption = [] // 付款账期
  collectionPeriod = {}//付款账期
  fujianNumber: any = 0
  isStartApproval: any;
  constructor(private DialogService: DialogService, private Router: Router, private UserService: UserService, private PurchaseService: PurchaseService, private CustomerService: CustomerService, private DataSharingService: DataSharingService, private ActivatedRoute: ActivatedRoute,private ReviewRolesService:ReviewRolesService) { }
  ngOnInit(): void {
    const userinfoString = localStorage.getItem('userinfo');
    if (userinfoString) {
      this.purchaseReturnOrder.creator = JSON.parse(userinfoString).username;
    }
    this.CustomerService.GetPagedCurrency(1, 9999).subscribe((res: any) => {
      this.currencyOption = res.items
    })
    this.CustomerService.GetPagedCollectionPeriod({
      PageSize: 999,
      PageNumber: 1,
      SearchStatus: '付款'
    }).subscribe((res: any) => {
      this.collectionPeriodOption = res.items
    })
    this.CustomerService.GetPagedSettlementMethod(1, 9999).subscribe((res: any) => {
      this.settlementMethodOption = res.items
    })
    this.ActivatedRoute.params.subscribe((params) => {
      if (params.id) {
        this.PurchaseService.getPurchaseReturnById(params.id).subscribe((res: any) => {
          this.purchaseReturnOrder = res
          this.purchaseReturnOrder.orderDate = new Date(res.orderDate)
          this.supplyContact = { supplyContactId: this.purchaseReturnOrder.supplyContactId, supplyContactName: this.purchaseReturnOrder.supplyContactName }
          this.currency = { currencyId: this.purchaseReturnOrder.proCurrencyId, currencyName: this.purchaseReturnOrder.currencyName }
          this.settlementMethod = { settlementMethodId: this.purchaseReturnOrder.proSettlementMethodId, settlementMethodName: this.purchaseReturnOrder.settlementMethodName }
          this.collectionPeriod = { collectionPeriodId: this.purchaseReturnOrder.proCollectionPeriodId, collectionPeriodName: this.purchaseReturnOrder.collectionPeriodName }
          this.purchaseReturnOrder.purchaseReturnedOrderParts.forEach(part => {
            part.returnedDate = new Date(part.returnedDate)
          })
          this.fujianNumber = this.purchaseReturnOrder.files.length
        })
      }
    })
  }

  showToast(type: any, summary: any, content: any) {
    switch (type) {
      default:
        this.msgs = [{ severity: type, summary: summary, content: content }];
    }
  }//提示框
  addRow() {
    this.purchaseReturnOrder.purchaseReturnedOrderParts.push(
      {
        purchaseReturnedOrderPartId: 0,
        partNum: '',
        partUOM: '',
        partName: '',
        description: '',
        partType: '',
        image: '',
        returnedQuantity: 0,
        returnedDate: undefined,
        warehouseId: 0,
        warehouseName: '',
        warehouseNum: '',
        positionId: 0,
        positionName: '',
        positionNum: '',
        priceWithTax: 0,
        priceWithoutTax: 0,
        taxRate: 0,
        amountWithTax: 0,
        amountWithoutTax: 0,
        taxAmount: 0,
        propPartId: 0,
        alreadyReturnedQuantity: 0,
        note: '',
        purchaseArrivalOrderNum: '',
        purchaseArrivalOrderPartId: 0,
        propPurchaseReturnedId: 0,
        purchaseReturnedOrderNum: ''
      }
  )
  }//添加行
  addRowA(item:any,index:any) {
    const newItem = JSON.parse(JSON.stringify(item));
    newItem.purchaseReturnOrderPartId = 0;
    newItem.returnedDate = new Date(newItem.returnedDate) || new Date();
    newItem.returnedQuantity = 0;
    this.purchaseReturnOrder.purchaseReturnedOrderParts.splice(index + 1, 0, newItem);
    this.calculateAmount(newItem);
  }//添加行
  deleteRow(index: number) {
    this.purchaseReturnOrder.purchaseReturnedOrderParts.splice(index, 1);
    if (this.purchaseReturnOrder.purchaseReturnedOrderParts.length == 0) {
      this.addRow()
    }
    this.calculateTotalAmount();
  }
  submit($event: any) {
    if ($event.valid) {
      if (!this.validatePurchaseArrival(this.purchaseReturnOrder)) {
        return;
      }
      this.purchaseReturnOrder.purchaseReturnedOrderParts.forEach((item) => {
        item.purchaseReturnedOrderNum = this.purchaseReturnOrder.purchaseReturnedOrderNum;
      })
      this.PurchaseService.editPurchaseReturn(this.purchaseReturnOrder.purchaseReturnedOrderId,this.purchaseReturnOrder).subscribe((res: any) => {
        if(this.isStartApproval){
          this.ReviewRolesService.StartApprovalFlow('采购退货单审核流配置',[this.purchaseReturnOrder.purchaseReturnedOrderNum]).subscribe((res:any)=>{
            this.showToast('success', '成功', '提交成功')
            setTimeout(() => {
              this.cancel()
            }, 1000);
          },(error)=>{
            this.showToast('error', '失败', '单据创建成功，审核流未启动');
            setTimeout(() => {
              this.cancel()
            },1000)
          }
        )
        }else{
          this.showToast('success', '成功', '提交成功')
          setTimeout(() => {
            this.cancel()
          }, 1000);
        }
        this.showToast('success', '成功', '提交成功')
        setTimeout(() => {
          this.cancel()
        }, 1000);
      },(error) => {
        if(error.status==404){
          this.showToast('error', '失败', '服务器连接失败');
        }else{
          this.showToast('error', '失败', error.error);
        }
      }
      )
    } else {
      this.showToast('warn', '错误', '请检查表单是否填写正确')
    }
  }
  getImagesArray(fileURL: string): string[] {
    let urls = fileURL.split(',');
    urls = urls.map(url => environment.modifiedApiUrl + url);
    return urls;
  }
  cancel() {
    this.Router.navigateByUrl('/pages/purchase/purchase-return')
  }
  fujian(dialogtype?: string) {
    const results = this.DialogService.open({
      title: '采购价格表附件',
      width: '800px',
      backdropCloseable: false,
      data: {
        data: '采购附件',
        urls: this.purchaseReturnOrder.files
      },
      content: AttachmentComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            this.purchaseReturnOrder.files.push(results.modalContentInstance.urls)
            this.fujianNumber = this.purchaseReturnOrder.files.length
            results.modalInstance.hide();
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  validatePurchaseArrival(purchaseReturnedOrder: PurchaseReturnedOrder): boolean {
    for (const [index, item] of purchaseReturnedOrder.purchaseReturnedOrderParts.entries()) {
      if (!item.partNum) {
        this.showToast('warn', '错误', `第${index + 1}行物料编码不能为空`);
        return false;
      }
      if (item.returnedQuantity <= 0) {
        this.showToast('warn', '错误', `第${index + 1}行数量必须大于0`);
        return false;
      }

    }
    return true;
  }   //所有验证通过
  selectUser() {
    const results = this.DialogService.open({
      id: 'Add',
      maxHeight: '400px',
      width: '800px',
      backdropCloseable: true,
      data: "",
      title: '选择业务员',
      content: SelectUserComponent,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            this.purchaseReturnOrder.purchaseManName = results.modalContentInstance.selectData.name;
            this.purchaseReturnOrder.purchaseManId = results.modalContentInstance.selectData.id;
            this.UserService.GetDepartmentById(results.modalContentInstance.selectData.departmentId).subscribe((res: any) => {
              this.purchaseReturnOrder.departmentName = res.name;
              this.purchaseReturnOrder.departmentId = res.departmentId;
            })
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    })
  }
  selectDepartment() {
    if (!this.purchaseReturnOrder.purchaseManId) {
      this.showToast('warn', '请选择业务员', '请选择业务员')
    }
  }
  selectSupply() {
    const results = this.DialogService.open({
      id: 'Add',
      maxHeight: '400px',
      width: '800px',
      backdropCloseable: true,
      data: "",
      title: '选择供应商',
      content: SelectSupplierComponent,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            this.purchaseReturnOrder.supplyShortName = results.modalContentInstance.selectData.supplyShortName;
            this.purchaseReturnOrder.proSupplyId = results.modalContentInstance.selectData.supplyId;
            this.purchaseReturnOrder.supplyChineseName = results.modalContentInstance.selectData.supplyChineseName;
            this.purchaseReturnOrder.supplyEnglishName = results.modalContentInstance.selectData.supplyEnglishName;
            this.purchaseReturnOrder.purchaseManName = results.modalContentInstance.selectData.salesmanName;
            this.purchaseReturnOrder.purchaseManId = results.modalContentInstance.selectData.salesmanId;
            this.UserService.GetUserById(results.modalContentInstance.selectData.salesmanId).subscribe((res: any) => {
              this.purchaseReturnOrder.departmentId = res.departmentId;
              this.UserService.GetDepartmentById(res.departmentId).subscribe((res: any) => {
                this.purchaseReturnOrder.departmentName = res.name;
              })
            })
            this.purchaseReturnOrder.supplyContactId = results.modalContentInstance.selectData.supplyContacts.find((contact: { isDefault: boolean; }) => contact.isDefault === true)?.supplyContactId;
            this.purchaseReturnOrder.supplyContactName = results.modalContentInstance.selectData.supplyContacts.find((contact: { isDefault: boolean; }) => contact.isDefault === true)?.supplyContactName;
            results.modalInstance.hide();
            this.supplyContact = { supplyContactId: this.purchaseReturnOrder.supplyContactId, supplyContactName: this.purchaseReturnOrder.supplyContactName }
            this.currency = { currencyId: results.modalContentInstance.selectData.supplyCurrencyId, currencyName: results.modalContentInstance.selectData.currencyName }
            this.settlementMethod = { settlementMethodId: results.modalContentInstance.selectData.supplySettlementMethodId, settlementMethodName: results.modalContentInstance.selectData.settlementMethodName }
            this.collectionPeriod = { collectionPeriodId: results.modalContentInstance.selectData.supplyCollectionPeriodId, collectionPeriodName: results.modalContentInstance.selectData.collectionPeriodName }
            this.purchaseReturnOrder.proSettlementMethodId = results.modalContentInstance.selectData.supplySettlementMethodId
            this.purchaseReturnOrder.settlementMethodName = results.modalContentInstance.selectData.settlementMethodName
            this.purchaseReturnOrder.proCurrencyId = results.modalContentInstance.selectData.supplyCurrencyId
            this.purchaseReturnOrder.currencyName = results.modalContentInstance.selectData.currencyName
            this.purchaseReturnOrder.proCollectionPeriodId = results.modalContentInstance.selectData.supplyCollectionPeriodId
            this.purchaseReturnOrder.collectionPeriodName = results.modalContentInstance.selectData.collectionPeriodName
            this.purchaseReturnOrder.purchaseReturnedOrderParts = []
            this.addRow()
            this.purchaseReturnOrder.purchaseReturnedOrderParts.map((item: any) => {
              this.calculateAmount(item);
            })
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  selectSupplier(dialogtype?: string) {
    if(this.purchaseReturnOrder.purchaseReturnedOrderParts[0].partNum){
      const results = this.DialogService.open({
        id: 'dialog-service',
        maxHeight: '400px',
        width: '300px',
        backdropCloseable: true,
        data: "",
        title: '',
        dialogtype: dialogtype,
        html: true,
        content: '<div style="color:#8a6d3b;font-size: 14px;">确定切换供应商，这将会使您构建的物料行数据重置！</div>',
        onClose: () => {
        },
        buttons: [
          {
            cssClass: 'stress',
            text: '确定',
            handler: ($event: Event) => {
              results.modalInstance.hide();
              this.selectSupply()
            },
          },
          {
            id: 'btn-cancel',
            cssClass: 'common',
            text: '取消',
            handler: ($event: Event) => {
              results.modalInstance.hide();
            },
          },
        ],
      });
    }else{
      this.selectSupply()
    }
  }
  selectSupplyContact($event: any) {
    this.purchaseReturnOrder.supplyContactId = $event.supplyContactId
    this.purchaseReturnOrder.supplyContactName = $event.supplyContactName
  }
  selectcurrency($event: any) {
    this.purchaseReturnOrder.proCurrencyId = $event.currencyId
    this.purchaseReturnOrder.currencyName = $event.currencyName
  }
  selectsettlementMethodOption($event: any) {
    this.purchaseReturnOrder.proSettlementMethodId = $event.settlementMethodId
    this.purchaseReturnOrder.settlementMethodName = $event.settlementMethodName
  }
  selectcollectionPeriodOption($event: any) {
    this.purchaseReturnOrder.proCollectionPeriodId = $event.collectionPeriodId
    this.purchaseReturnOrder.collectionPeriodName = $event.collectionPeriodName
  }
  taxRateChange(rowitem: any, value: number) {
    rowitem.taxRate = value / 100;
    this.calculateAmount(rowitem);
  }//税率改变
  quantityChange(rowitem: any, value: number) {
    rowitem.returnedQuantity = value;
    this.calculateAmount(rowitem);
  }//采购数量改变
  priceWithTaxChange(rowitem: any, value: number) {
    rowitem.priceWithTax = value;
    this.calculateAmount(rowitem);
  }//含税单价改变
  calculateAmount(item: any): void {
    //计算不含税单价，并保留6位小数
    item.priceWithoutTax = +(item.priceWithTax / (1 + item.taxRate)).toFixed(4);
    item.amountWithTax = +(item.priceWithTax * item.returnedQuantity).toFixed(4);
    item.taxAmount = +((item.priceWithTax - item.priceWithoutTax) * item.returnedQuantity).toFixed(4);
    item.amountWithoutTax = +(item.amountWithTax - item.taxAmount).toFixed(4);
    this.calculateTotalAmount()
  }
  calculateTotalAmount(): void {
    this.purchaseReturnOrder.returnedQuantity = this.purchaseReturnOrder.purchaseReturnedOrderParts.reduce((pre, cur) => {
      return pre + cur.returnedQuantity;
    },0);
    this.purchaseReturnOrder.totalAmountWithTax = this.purchaseReturnOrder.purchaseReturnedOrderParts.reduce((pre, cur) => {
      return pre + cur.amountWithTax;
    }, 0);
    this.purchaseReturnOrder.totalAmountWithoutTax = this.purchaseReturnOrder.purchaseReturnedOrderParts.reduce((pre, cur) => {
      return pre + cur.amountWithoutTax;
    }, 0);
    this.purchaseReturnOrder.totalTaxAmount = this.purchaseReturnOrder.purchaseReturnedOrderParts.reduce((pre, cur) => {
      return pre + cur.taxAmount;
    }, 0);
  }
  selectPurchaseOrder(dialogtype?: string) {
    const purchaseOrderPartIds = this.purchaseReturnOrder.purchaseReturnedOrderParts.map((item: { purchaseArrivalOrderPartId: any; }) => item.purchaseArrivalOrderPartId);
    const results = this.DialogService.open({
      id: 'Add',
      width: '1200px',
      backdropCloseable: true,
      data: purchaseOrderPartIds,
      title: '选择采购到货单',
      content: SelectArrivalComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            results.modalContentInstance.getCheckedRowsData()
            if (results.modalContentInstance.CheckedRows.every(
              (item: { paoSupplyId: any; }, index: any, array: { paoSupplyId: any; }[]) => item.paoSupplyId === array[0].paoSupplyId
            )) {
              this.purchaseReturnOrder.proSupplyId = results.modalContentInstance.CheckedRows[0].paoSupplyId;
              this.purchaseReturnOrder.supplyShortName = results.modalContentInstance.CheckedRows[0].supplyShortName;
              this.purchaseReturnOrder.supplyChineseName = results.modalContentInstance.CheckedRows[0].supplyChineseName;
              this.purchaseReturnOrder.supplyEnglishName = results.modalContentInstance.CheckedRows[0].supplyEnglishName;
              this.purchaseReturnOrder.supplyContactName = results.modalContentInstance.CheckedRows[0].supplyContactName;
              this.purchaseReturnOrder.supplyContactId = results.modalContentInstance.CheckedRows[0].supplyContactId;
              this.supplyContact = { supplyContactId: this.purchaseReturnOrder.supplyContactId, supplyContactName: this.purchaseReturnOrder.supplyContactName }
              this.purchaseReturnOrder.purchaseManName = results.modalContentInstance.CheckedRows[0].purchaseManName;
              this.purchaseReturnOrder.purchaseManId = results.modalContentInstance.CheckedRows[0].purchaseManId;
              this.purchaseReturnOrder.departmentName = results.modalContentInstance.CheckedRows[0].departmentName;
              this.purchaseReturnOrder.departmentId = results.modalContentInstance.CheckedRows[0].departmentId;
              this.purchaseReturnOrder.proSettlementMethodId = results.modalContentInstance.CheckedRows[0].paoSettlementMethodId;
              this.purchaseReturnOrder.settlementMethodName = results.modalContentInstance.CheckedRows[0].settlementMethodName;
              this.purchaseReturnOrder.proCurrencyId = results.modalContentInstance.CheckedRows[0].paoCurrencyId;
              this.purchaseReturnOrder.currencyName = results.modalContentInstance.CheckedRows[0].currencyName;
              this.purchaseReturnOrder.proCollectionPeriodId = results.modalContentInstance.CheckedRows[0].paoCollectionPeriodId;
              this.purchaseReturnOrder.collectionPeriodName = results.modalContentInstance.CheckedRows[0].collectionPeriodName;
              this.purchaseReturnOrder.purchaseReturnedOrderParts = this.purchaseReturnOrder.purchaseReturnedOrderParts.filter(
                (item: any) => item.propPartId !== 0 && item.propPartId !== null
              );
              const newPurchaseReturnedOrderParts = results.modalContentInstance.filterRows.map((item: any) => {
                return {
                  purchaseReturnedOrderPartId: 0, // 采购退货订单物料行ID，初始化为0
                  partNum: item.partNum || "", // 物料编号，初始化为空字符串
                  partUOM: item.partUOM || "", // 物料单位，初始化为空字符串
                  partName: item.partName || "", // 物料名称，初始化为空字符串
                  description: item.description || "", // 物料描述，初始化为空字符串
                  partType: item.partType || "", // 规格型号，初始化为空字符串
                  image: item.image || "", // 图片，初始化为空字符串
                  returnedQuantity: item.arrivalQuantity - item.returnedQuantity, // 退货数量
                  returnedDate: new Date(), // 退货日期，初始化为当前日期
                  warehouseId: item.warehouseId || 0, // 仓库ID，初始化为0
                  warehouseName: item.warehouseName || "", // 仓库名称，初始化为空字符串
                  warehouseNum: item.warehouseNum || "", // 仓库编号，初始化为空字符串
                  positionId: item.positionId || 0, // 位置ID，初始化为0
                  positionName: item.positionName || "", // 位置名称，初始化为空字符串
                  positionNum: item.positionNum || "", // 位置编号，初始化为空字符串
                  priceWithTax: item.priceWithTax || 0, // 含税价格，初始化为0
                  priceWithoutTax: 0, // 不含税价格，初始化为0
                  taxRate: item.taxRate || 0, // 税率，初始化为0
                  amountWithTax: 0, // 含税金额，初始化为0
                  amountWithoutTax: 0, // 不含税金额，初始化为0
                  taxAmount: 0, // 税额，初始化为0
                  propPartId: item.paoPartId || 0, // 部件ID，初始化为0
                  alreadyReturnedQuantity: 0, // 已退货数量，初始化为0
                  note: item.note || "", // 备注，初始化为空字符串
                  purchaseArrivalOrderNum: item.purchaseArrivalOrderNum || "", // 采购到货订单编号，初始化为空字符串
                  purchaseArrivalOrderPartId: item.purchaseArrivalOrderPartId || 0, // 采购到货订单物料行ID，初始化为0
                  propPurchaseReturnedId: 0, // 采购退货订单ID，初始化为0
                  purchaseReturnedOrderNum: "" // 采购退货订单编号，初始化为空字符串
                };
              });
              this.purchaseReturnOrder.purchaseReturnedOrderParts = this.purchaseReturnOrder.purchaseReturnedOrderParts.concat(newPurchaseReturnedOrderParts);
              this.calculateTotalAmount();
              if(this.purchaseReturnOrder.purchaseReturnedOrderParts.length==0){
                this.addRow()
              }
              results.modalInstance.hide();
              this.purchaseReturnOrder.purchaseReturnedOrderParts.forEach(part => {
                this.calculateAmount(part);
              });
            }else{
              this.showToast('warn', '错误', '请选择相同供应商的采购订单')
            }

          }
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        }
      ]
    })
  }
  selectWarehouse(rowitem: any) {
    if (rowitem) {
      if (!rowitem.partNum) {
        this.showToast('warn', '错误', '没有物料数据');
        return;
      }
    }
    const results = this.DialogService.open({
      id: 'Add',
      width: '800px',
      backdropCloseable: true,
      data: rowitem,
      title: '选择仓库',
      content: SelectInventoryComponent,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            rowitem.warehouseId = results.modalContentInstance.selectData.warehouseId;
            rowitem.warehouseName = results.modalContentInstance.selectData.warehouseName;
            rowitem.warehouseNum = results.modalContentInstance.selectData.warehouseNum;
            rowitem.positionId = results.modalContentInstance.selectData.positionId;
            rowitem.positionName = results.modalContentInstance.selectData.positionName;
            rowitem.positionNum = results.modalContentInstance.selectData.positionNum;
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
}
